<template>
    <div>
        <el-dialog :title="isAdd ? '添加商品' : '编辑商品'" :visible.sync="isShow" center :before-close="cancel" @opened="createEditor">
            <el-form :model="goodsForm" ref="goodsinfo" :rules="rules">
                <el-form-item prop="first_cateid" label="一级分类" :label-width="formLabelWidth">
                    <el-select v-model="goodsForm.first_cateid" placeholder="请选泽" @change="changeCate(false)">
                        <el-option v-for="item in catelist" :key="item.id" :value="item.id" :label="item.catename">
                        </el-option>
                    </el-select>
                </el-form-item>

                <el-form-item prop="second_cateid" label="二级分类" :label-width="formLabelWidth">
                    <el-select v-model="goodsForm.second_cateid" placeholder="请选泽">
                        <el-option v-for="item in secondCateArr" :key="item.id" :value="item.id" :label="item.catename">
                        </el-option>
                    </el-select>
                </el-form-item>

                <el-form-item label="商品名称" :label-width="formLabelWidth" prop="goodsname">
                    <el-input v-model="goodsForm.goodsname" autocomplete="off"></el-input>
                </el-form-item>

                <el-form-item label="价格" :label-width="formLabelWidth" prop="price">
                    <el-input v-model="goodsForm.price" autocomplete="off"></el-input>
                </el-form-item>

                <el-form-item label="市场价格" :label-width="formLabelWidth" prop="market_price">
                    <el-input v-model="goodsForm.market_price" autocomplete="off"></el-input>
                </el-form-item>

                <el-form-item label="图片" :label-width="formLabelWidth">
                    <el-upload action="#" list-type="picture-card" :on-preview="onPreview" :on-remove="handleRemove"
                        :auto-upload="false" :on-change="onChange" :file-list="fileList" :limit="1"
                        :on-exceed="onExceed">
                        <i class="el-icon-plus"></i>
                    </el-upload>
                    <el-dialog :visible.sync="dialogVisible">
                        <img width="100%" :src="dialogImageUrl" alt="" />
                    </el-dialog>
                </el-form-item>

                <el-form-item label="商品规格" :label-width="formLabelWidth" prop="specsid">
                    <el-select v-model="goodsForm.specsid" placeholder="请选择" @change="changeSpecs(false)">
                        <el-option v-for="item in specsArr" :key="item.id" :value="item.id"
                            :label="item.specsname"></el-option>
                    </el-select>
                </el-form-item>

                <el-form-item label="规格属性" :label-width="formLabelWidth" prop="specsattr">
                    <!-- multiple 下拉框是否多选 -->
                    <el-select v-model="goodsForm.specsattr" placeholder="请选择" multiple>
                        <el-option v-for="item in attrArr" :key="item" :value="item" :label="item"></el-option>
                    </el-select>
                </el-form-item>

                <el-form-item label="是否新品" :label-width="formLabelWidth">
                    <el-radio v-model="goodsForm.isnew" :label="1">是</el-radio>
                    <el-radio v-model="goodsForm.isnew" :label="2">否</el-radio>
                </el-form-item>

                <el-form-item label="是否热卖" :label-width="formLabelWidth">
                    <el-radio v-model="goodsForm.ishot" :label="1">是</el-radio>
                    <el-radio v-model="goodsForm.ishot" :label="2">否</el-radio>
                </el-form-item>

                <el-form-item label="商品描述" :label-width="formLabelWidth">
                    <div id="editor"></div>
                </el-form-item>

                <el-form-item label="状态" :label-width="formLabelWidth">
                    <el-switch v-model="goodsForm.status" active-color="#13ce66" inactive-color="#ff4949"
                        :active-value="1" :inactive-value="2">
                    </el-switch>
                </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button @click="cancel">取 消</el-button>
                <el-button type="primary" @click="confirm">确 定</el-button>
            </div>
        </el-dialog>
    </div>
</template>

<script>
import { mapGetters, mapActions } from 'vuex'
import { goodsAdd, specsList, goodsEdit, goodsInfo } from '../../request/api'
import E from 'wangeditor'
export default {
    props: ['isShow', 'isAdd'],
    data() {
        return {
            formLabelWidth: '120px',
            dialogImageUrl: '',
            dialogVisible: false,
            fileList: [],
            goodsForm: {
                first_cateid: "",
                second_cateid: "",
                goodsname: "",
                price: "",
                market_price: "",
                img: "",
                specsid: '',
                specsattr: "",
                isnew: 1,
                ishot: 1,
                status: 1,
                description: "",
            },
            rules: {
                first_cateid: [
                    { required: true, message: "请选择一级分类", trigger: "change" },
                ],
                second_cateid: [
                    { required: true, message: "请选择二级分类", trigger: "blur" },
                ],
                goodsname: [
                    { required: true, message: "请输入商品名称", trigger: "blur" },
                    {
                        min: 2,
                        max: 15,
                        message: "长度在 2 到 15 个字符",
                        trigger: "blur",
                    },
                ],
                price: [{ required: true, message: "请输入商品价格", trigger: "blur" }],
                market_price: [
                    { required: true, message: "请输入市场价格", trigger: "blur" },
                ],
                specsid: [
                    { required: true, message: "请选择商品规格", trigger: "change" },
                ],
                specsattr: [
                    { required: true, message: "请选择规格属性", trigger: "blur" },
                ],
            },
            secondCateArr: [],//二级分类列表
            specsArr: [],
            attrArr: [],
            editor: null
        }
    },
    computed: {
        ...mapGetters({
            catelist: 'cate/getCateList'
        })
    },
    mounted() {
        this.getCateAction()
        this.getSpecs()
    },
    methods: {
        //封装创建编辑器的方法
        createEditor() {
            this.editor = new E('#editor')
            this.editor.create()
            this.editor.txt.html(this.goodsForm.description)
        },
        //获取商品规格的接口
        getSpecs() {
            specsList().then(res => {
                this.specsArr = res.list
            })
        },
        ...mapActions({
            getCateAction: 'cate/changeCateAction',
            getGoods: 'goods/getGoodsAction',
            getCount: 'goods/getCountAction'
        }),
        changeSpecs(n) {
            let index = this.specsArr.findIndex(item => this.goodsForm.specsid == item.id)
            this.attrArr = this.specsArr[index].attrs
            if (!n) {
                this.goodsForm.specsattr = []
            }
        },
        //一级分类获取二级分类事件
        changeCate(n) {
            let index = this.catelist.findIndex(item => this.goodsForm.first_cateid == item.id)
            this.secondCateArr = this.catelist[index].children
            //清空二级分类双向数据绑定值
            if (!n) {
                this.goodsForm.second_cateid = "";
            }
        },
        //文件限制方法
        onExceed(files, fileList) {
            this.$message.warning(`当前限制选择1个文件,本次选择了${files.length}个文件,共选择了${files.length + fileList.length}个文件`)
        },
        //预览的回调函数
        onPreview(file) {
            console.log(file, '文件');
            this.dialogImageUrl = file.url
            this.dialogVisible = true
        },
        handleRemove(file, fileList) { },
        onChange(file, fileList) {
            this.goodsForm.img = file.raw
        },
        cancel() {
            this.$emit('cancel', false)
            this.reset()
        },
        reset() {
            this.goodsForm = {
                first_cateid: "",
                second_cateid: "",
                goodsname: "",
                price: "",
                market_price: "",
                img: "",
                specsid: '',
                specsattr: "",
                isnew: 1,
                ishot: 1,
                status: 1,
                description: "",
            }
            this.$refs.goodsinfo.resetFields()
            this.fileList = []
            this.editor.destroy()
        },
        lookup(id) {
            goodsInfo({ id }).then(res => {
                if (res.code == 200) {
                    this.goodsForm = res.list
                    this.fileList = this.goodsForm.img ? [{ url: this.goodsForm.img }] : []
                    this.goodsForm.id = id
                    this.goodsForm.specsattr = this.goodsForm.specsattr.split(',')
                    this.changeCate(true)
                    this.changeSpecs(true)
                    this.editor.txt.html(this.goodsForm.description)
                } else {
                    this.$message.error(res.msg)
                }
            })
        },
        confirm() {
            this.$refs.goodsinfo.validate(val => {
                if (val) {
                    this.goodsForm.specsattr = this.goodsForm.specsattr.join(',')
                    this.goodsForm.description = this.editor.txt.html()
                    if (this.isAdd) {
                        //添加商品接口
                        goodsAdd(this.goodsForm).then(res => {
                            console.log(res);
                            if (res.code == 200) {
                                this.$message.success(res.msg)
                                this.getGoods()
                                this.getCount()
                                this.cancel()
                            } else {
                                this.$message.error(res.msg)
                            }
                        })
                    } else {
                        //编辑商品接口
                        goodsEdit(this.goodsForm).then(res => {
                            if (res.code == 200) {
                                this.$message.success(res.msg)
                                this.getGoods()
                                this.getCount()
                                this.cancel()
                            } else {
                                this.$message.error(res.msg)
                            }
                        })
                    }
                } else {
                    this.$message.error("验证失败");
                    return false;
                }
            })
        }
    }
}
</script>

<style scoped>

</style>